from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List

from app.schemas.response import BaseResponse
from app.crud.user import get_user, create_user,  get_user_by_username, get_users
from app.db.session import get_db
from app.schemas.user import UserCreate, User

router = APIRouter()

@router.post("/", response_model=BaseResponse[User])
def create_user_endpoint(user: UserCreate, db: Session = Depends(get_db)):
    db_user = get_user_by_username(db, username=user.username)
    if db_user:
        raise HTTPException(status_code=400, detail="Username already registered")
    created_user = create_user(db=db, user=user)
    return BaseResponse(data=created_user)

@router.get("/{user_id}", response_model=BaseResponse[User])
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return BaseResponse(data=db_user)

@router.get("/", response_model=BaseResponse[List[User]])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = get_users(db, skip=skip, limit=limit)
    return BaseResponse(data=users)